import { Coupon } from './coupon-model.js';
var coupon = new Coupon();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showInput:false,
    getting:false,
    getText:"确认领取"
  },
  onLoad: function (options) {
    var id = options.id ? options.id : '';
    this.data.id = id;
    if(!id){
      wx.showToast({
        title: '参数有误',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    wx.setStorageSync('redirect-url', '/pages/coupon/friend?id=' + id);
    this.getCardInfo(id);
  },
  onReady: function () {

  },
  //获取卡券信息
  getCardInfo:function(id){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    var args = {
      id : id
    }
    that.setData({
      loadingHidden: false
    })
    coupon.getShareCouponInfo(args, (res) => {
      wx.hideLoading()
      res.coupon.use_end = util.formatTime(res.coupon.use_end, "Y-M-D")
      that.setData({
        item: res,
      });
    });
  },

  //领取卡
  receive:function(){
    this.setData({
      showInput: true
    })
  },
  //确认领取卡券
  receiveAction:function(){
    var that = this;
    if (!this.data.code){
      wx.showToast({
        title: '请填写转赠码，可询问好友获取！',
        icon: 'none',
        duration: 3000,
      })
      return false;
    }
    var args = {
      item_id :this.data.id,
      password: this.data.code
    }
    if(this.data.getting)
    {
      return false;
    }
    this.data.getting = true;
    that.setData({getText:'正在领取...'})
    coupon.friendReceive(args, (res) => {
      that.data.getting = false;
      that.setData({ getText: '确认领取' })
      if (res.status == 1) {
        wx.showToast({
          title: '领取成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            wx.redirectTo({
              url: '../coupon/my',
            })
          }
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  //获取输入的转赠码内容
  code: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  //关闭弹窗
  hideModal: function (e) {
    this.setData({
      showInput: false
    })
  },
})